using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using Application.Web.Core.Services;
using Application.Service.Auth;
using Application.Service.LogCache;

namespace Application.Web.Entry.Pages
{
    public partial class Login : ComponentBase
    {
        [Inject]
        private NavigationManager Navigation { get; set; } = null!;

        [Inject]
        private AuthService AuthService { get; set; } = null!;

        [Inject]
        private IJSRuntime JSRuntime { get; set; } = null!;

        [Inject]
        private LockScreen LockScreenService { get; set; } = null!;

        private LoginModel loginModel = new LoginModel();
        private string errorMessage = string.Empty;
        private bool isLoading = false;
        private bool passwdHash = false;

        protected override async Task OnInitializedAsync()
        {
            await LoadRememberedCredentials();
        }

        private async Task LoadRememberedCredentials()
        {
            try
            {
                // 加载记住的用户名
                var rememberedUsername = await JSRuntime.InvokeAsync<string>("localStorage.getItem", "rememberedUsername");
                if (!string.IsNullOrEmpty(rememberedUsername))
                {
                    loginModel.Username = rememberedUsername;
                }

				loginModel.RememberPassword = bool.Parse(await JSRuntime.InvokeAsync<string>("localStorage.getItem", "remembered"));

				// 加载记住的密码
				var rememberedPassword = await JSRuntime.InvokeAsync<string>("localStorage.getItem", "rememberedPassword");
                if (!string.IsNullOrEmpty(rememberedPassword))
                {
                    loginModel.Password = rememberedPassword;
                    loginModel.RememberPassword = loginModel.RememberPassword;
                }
            }
            catch
            {
                // 忽略错误，可能在不支持localStorage的环境中运行
            }
        }

        private async Task HandleLogin()
        {
            isLoading = true;
            
            errorMessage = string.Empty;

            var result = await AuthService.LoginAsync(loginModel.Username, Furion.DataEncryption.MD5Encryption.Encrypt($"{Furion.App.GetConfig<string>("SecretKey")}{loginModel.Password}"));

            if(!result.Success && loginModel.RememberPassword)             
            {
				result = await AuthService.LoginAsync(loginModel.Username, loginModel.Password);
				passwdHash = result.Success;
			}

			if (result.Success)
            {
                // 此处记住当前登录用户名和用户Id
                await JSRuntime.InvokeVoidAsync("localStorage.setItem", "currentUserId", result.UserId.ToString());
                await JSRuntime.InvokeVoidAsync("localStorage.setItem", "currentUserName", loginModel.Username);
                await JSRuntime.InvokeVoidAsync("localStorage.setItem", "currentDisplayName", result.DisplayName);
                


				// 如果选择了记住密码，保存用户名和密码到localStorage
				if (loginModel.RememberPassword)
                {
                    await JSRuntime.InvokeVoidAsync("localStorage.setItem", "rememberedUsername", loginModel.Username);
                    await JSRuntime.InvokeVoidAsync("localStorage.setItem", "rememberedPassword", passwdHash? loginModel.Password:Furion.DataEncryption.MD5Encryption.Encrypt($"{Furion.App.GetConfig<string>("SecretKey")}{loginModel.Password}"));
					await JSRuntime.InvokeVoidAsync("localStorage.setItem", "remembered", loginModel.RememberPassword);
				}
                else
                {
                    await JSRuntime.InvokeVoidAsync("localStorage.removeItem", "rememberedUsername");
                    await JSRuntime.InvokeVoidAsync("localStorage.removeItem", "rememberedPassword");
					await JSRuntime.InvokeVoidAsync("localStorage.removeItem", "remembered");
				}


                // 登录成功后启动锁屏计时器
                LockScreenService.StartLockScreenTimer();

                // 登录成功后清空日志缓存
                LogWrapper.Clear();
                LogWrapper.Information("登录成功");
                // 登录成功，跳转到首页
                Navigation.NavigateTo("/", true);
            }
            else
            {
                // 根据错误类型设置相应的错误状态
                if (result.ErrorMessage == "无此用户")
                {
                    loginModel.IsUsernameError = true;
                    loginModel.IsPasswordError = false;
                }
                else if (result.ErrorMessage == "密码错误")
                {
                    loginModel.IsUsernameError = false;
                    loginModel.IsPasswordError = true;
                }
                else if (result.ErrorMessage == "用户已在其他客户端登录")
                {
                    loginModel.IsUsernameError = false;
                    loginModel.IsPasswordError = false;
                    // 特殊处理：用户已在其他客户端登录
                }

                errorMessage = result.ErrorMessage;
            }

            isLoading = false;
        }

        private async Task OnUsernameBlur()
        {
            if (!string.IsNullOrEmpty(loginModel.Username))
            {
                var result = await AuthService.CheckUserAsync(loginModel.Username);
                loginModel.IsUsernameError = !result.Success;

                // 如果用户名存在，清除密码错误状态
                if (result.Success)
                {
                    loginModel.IsPasswordError = false;
                }
            }
            else
            {
                // 用户名为空时清除错误状态
                loginModel.IsUsernameError = false;
            }

            // 触发UI更新
            StateHasChanged();
        }

        public class LoginModel
        {
            [Required(ErrorMessage = "用户名不能为空")]
            public string Username { get; set; } = string.Empty;

            [Required(ErrorMessage = "密码不能为空")]
            public string Password { get; set; } = string.Empty;

            public bool RememberPassword { get; set; } = false;

            public bool IsUsernameError { get; set; }
            public bool IsPasswordError { get; set; }
        }
    }
}
